package io.afu.validator.Implement;

import io.afu.validator.Annimation.NumberStrValidator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NumberValidatorImpl implements ConstraintValidator<NumberStrValidator,String> {

    private boolean allowEmpty;

    private int exactDigit;

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (null == s || "".equals(s)){
            if (allowEmpty){
                return true;
            }
        }else {
            if (exactDigit<=-1){
                // 进行数值校验
                if (s.contains(".")){
                    String patten = "^(-?\\d+)(\\.\\d+)?$";
                    Pattern p = Pattern.compile(patten);
                    Matcher m = p.matcher(s);
                    return m.find();
                }else {
                    String patten = "^-?\\d+$";
                    Pattern p = Pattern.compile(patten);
                    Matcher m = p.matcher(s);
                    return m.find();
                }
            }else if (exactDigit == 0){
                // 进行整数的校验
                String patten = "^-?\\d+$";
                Pattern p = Pattern.compile(patten);
                Matcher m = p.matcher(s);
                return m.find();
            }else {
                // 进行小数位的精确校验
                String digitNum = String.valueOf(exactDigit);
                String patten = "^-?\\d++(.[0-9]{"+digitNum+"})?$";
                Pattern p = Pattern.compile(patten);
                Matcher m = p.matcher(s);
                return m.find();
            }
        }
        return false;
    }

    @Override
    public void initialize(NumberStrValidator constraintAnnotation) {
        this.allowEmpty = constraintAnnotation.allowEmpty();
        this.exactDigit = constraintAnnotation.exactDigit();
    }
}
